package org.restoran.controller.web;

import org.restoran.model.Identifiable;
import org.restoran.service.ServiceException;
import org.restoran.service.parser.jackson.ParsingDeserializException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * @author Snisar Bogdan.
 */
@Controller
public abstract class AbstractController {

    private static Logger log = LoggerFactory.getLogger(AbstractController.class);


    public static final String OK = "{\"success\":true, \"data\":";
    public static final String ERROR = "{\"success\":false}";
    public static final String END_STREAM = "}";

    protected String success() {
        return "{\"success\":true, \"data\":{}}";
    }

    protected String success(String message) {
        return new StringBuilder().
                append(OK).
                append(message).
                append(END_STREAM).
                toString();
    }

    protected String error() {
        return ERROR;
    }

    protected String error(String meseg) {
        return new StringBuilder().
                append("{\"success\":false, \"error\": {").
                append(meseg).
                append("}}").
                toString();
    }


    @ExceptionHandler(ParsingDeserializException.class)
    public ResponseEntity<String> jsonParsing(ParsingDeserializException e) {
        log.warn("Exception in parsing {}", e);

        return new ResponseEntity<>(
                error(String.format("\"id\":1001, \"message\":\" Invalid json data. %s\"", e.getMessage())),
                HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(DataAccessException.class)
    public ResponseEntity<String> databaseException(DataAccessException e) {
        log.warn("Exception in database {}", e);

        return new ResponseEntity<>(
                error(String.format("\"id\":1001, \"message\":\" Exception with database: %s\"", e.getMessage())),
                HttpStatus.BAD_GATEWAY);
    }

//    todo: service exception hierarchy
    @ExceptionHandler(ServiceException.class)
    public ResponseEntity<String> businessException(ServiceException e) {
        log.warn("Exception in bushiness logic {}", e);

        return new ResponseEntity<>(
                error(String.format("\"id\":1001, \"message\":\" Exception with database: %s\"", e.getMessage())),
                HttpStatus.UNPROCESSABLE_ENTITY
        );
    }

    protected void inspectEntityId(Identifiable<Integer> obj) {
        if(obj != null) obj.setId(obj.getId() == 0 ? null : obj.getId());
    }

}
